import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Popconfirm, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, DeploymentUnitOutlined } from '@ant-design/icons';
import { ModelApi, ModelVO } from '../../../api/bpm/model';

const BPMModel: React.FC = () => {
  const [models, setModels] = useState<ModelVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingModel, setEditingModel] = useState<ModelVO | null>(null);
  const [form] = Form.useForm();

  // 获取模型列表
  const fetchModels = async () => {
    setLoading(true);
    try {
      const response = await ModelApi.getModelList();
      setModels(response.data || []);
    } catch (error) {
      message.error('获取模型列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchModels();
  }, []);

  // 新增/编辑模型
  const handleSave = async (values: any) => {
    try {
      if (editingModel) {
        await ModelApi.updateModel({ ...editingModel, ...values });
        message.success('更新模型成功');
      } else {
        await ModelApi.createModel(values);
        message.success('创建模型成功');
      }
      setModalVisible(false);
      setEditingModel(null);
      form.resetFields();
      fetchModels();
    } catch (error) {
      message.error(editingModel ? '更新模型失败' : '创建模型失败');
    }
  };

  // 删除模型
  const handleDelete = async (id: number) => {
    try {
      await ModelApi.deleteModel(id);
      message.success('删除模型成功');
      fetchModels();
    } catch (error) {
      message.error('删除模型失败');
    }
  };

  // 部署模型
  const handleDeploy = async (id: number) => {
    try {
      await ModelApi.deployModel(id);
      message.success('部署模型成功');
      fetchModels();
    } catch (error) {
      message.error('部署模型失败');
    }
  };

  // 打开编辑模态框
  const openEditModal = (model: ModelVO) => {
    setEditingModel(model);
    form.setFieldsValue(model);
    setModalVisible(true);
  };

  // 打开新增模态框
  const openAddModal = () => {
    setEditingModel(null);
    form.resetFields();
    setModalVisible(true);
  };

  const columns = [
    {
      title: '模型名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '模型标识',
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'orange'}>
          {status === 1 ? '已部署' : '未部署'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: ModelVO) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<DeploymentUnitOutlined />}
            onClick={() => handleDeploy(record.id!)}
            disabled={record.status === 1}
          >
            部署
          </Button>
          <Popconfirm
            title="确定要删除这个模型吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={openAddModal}
        >
          新增模型
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={models}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      <Modal
        title={editingModel ? '编辑模型' : '新增模型'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingModel(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            name="name"
            label="模型名称"
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input placeholder="请输入模型名称" />
          </Form.Item>
          <Form.Item
            name="key"
            label="模型标识"
            rules={[{ required: true, message: '请输入模型标识' }]}
          >
            <Input placeholder="请输入模型标识" />
          </Form.Item>
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请输入分类' }]}
          >
            <Input placeholder="请输入分类" />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入描述" rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BPMModel;